/**
 * Created by zhangqingxi on 2017-04-06.
 */
var modelPath = ROOT_PATH + '/emergency/team/';



//初始化部门
function initDept() {

    $('#deptId').combotree({
        url: findDept,
        required:true,
        editable:false,
        prompt:'请选择',
        onSelect:function (record) {
            $("#name").textbox('setValue',record.text)
        }
    });
}
//初始化负责人
function initUser() {
    $("#chargePersonName").textbox({
        editable:false,
        required:true,
        iconWidth: 22,
        icons: [{
            iconCls: 'icon-add',
            handler: function (e) {
                add_userInfo_func();
            }
        }, {
            iconCls: 'icon-remove',
            handler: function (e) {
                $(e.data.target).textbox('clear');
                $('#chargePersonId').val('');

            }
        }]
    });
}
function add_userInfo_func() {
    WindowManager.openLayer({
        type: 2,
        title: '选择人员信息',
        area: ['1150px', '70%'],
        content: ROOT_PATH + '/permission/user/simpleList.shtml?isMulti=0',
        callBack: function (data) {//窗口关闭后的回调函数
            var id = data[0].id;
            var name = data[0].realName;

            $('#chargePersonId').val(id);
            $('#chargePersonName').textbox('setValue', name);

        }
    });

}
//初始化 队伍类型
function initType() {
    $('#typeId').combobox({
        url:dictionaryByCode+teamType,
        prompt:'请选择',
        required:true,
        editable:false,
        valueField:'id',
        textField:'text'
    });
}
//初始化 建制
function initSystem() {
    $('#systemId').combobox({
        url:dictionaryByCode+teamSystem,
        prompt:'请选择',
        required:true,
        editable:false,
        valueField:'id',
        textField:'text',
        onSelect:function (record) {
            hideDiv();
            $('#leader_div').show();
            $('#basicLevel_div').show();
            switch (record.code){
                case 'teamSystem_one':

                case 'teamSystem_two':

                    $('#functional_div').show();
                    break;
                case 'teamSystem_three':

                    break;
                case 'teamSystem_four':
                    $('#serviceArea_div').show();
                    break;

            }
        }
    });
}
//初始化 专业特色
function initMajor() {
    $('#majorId').combobox({
        url:dictionaryByCode+teamMajor,
        prompt:'请选择',
        required:true,
        editable:false,
        valueField:'id',
        textField:'text'
    });
}
//初始化 基地
function initBase() {
    $('#baseId').combobox({
        url:dictionaryByCode+teamBase,
        prompt:'请选择',
        required:true,
        editable:false,
        valueField:'id',
        textField:'text'
    });
}

/**
 * 初始化领导班子
 */
function initLeader() {
    var url='';
    var teamId=$('#teamId').val();
    if(teamId !== undefined){
        url=findTeamUser+teamId+"&userType=0"
    }
    $('#leader_table').datagrid({
        url:url,
        fitColumns: true,
        rownumbers: true,
        sortOrder: true,
        striped: true,
        fit: true,
        columns: [[
            {field: 'userId',  checkbox: true},
            {field: 'deptName', title: '所属部门', width: '20%'},
            {field: 'userName', title: '姓名', width: '20%'},
            {field: 'sex', title: '性别', width: '15%'},
            {field: 'postName', title: '岗位', width: '17%'},
            {field: 'age', title: '年龄', width: '15%'}

        ]],
        toolbar: 'leaderToolbar'
    });
}
function initFunctional() {
    var url='';
    var teamId=$('#teamId').val();
    if(teamId !== undefined){
        url=findTeamUser+teamId+"&userType=1"
    }
    $('#functional_table').datagrid({
        url:url,
        fitColumns: true,
        rownumbers: true,
        sortOrder: true,
        striped: true,
        fit: true,
        columns: [[
            {field: 'userId',  checkbox: true},
            {field: 'deptName', title: '所属部门', width: '20%'},
            {field: 'userName', title: '姓名', width: '20%'},
            {field: 'sex', title: '性别', width: '15%'},
            {field: 'postName', title: '岗位', width: '17%'},
            {field: 'age', title: '年龄', width: '15%'}
        ]],
        toolbar: 'functionalToolbar'
    });
}
function initBasicLevel() {
    var url='';
    var teamId=$('#teamId').val();
    if(teamId !== undefined){
        url=findTeamUser+teamId+"&userType=2"
    }
    $('#basicLevel_table').datagrid({
        url:url,
        fitColumns: true,
        rownumbers: true,
        sortOrder: true,
        striped: true,
        fit: true,
        columns: [[
            {field: 'userId',  checkbox: true},
            {field: 'deptName', title: '所属部门', width: '20%'},
            {field: 'userName', title: '姓名', width: '20%'},
            {field: 'sex', title: '性别', width: '15%'},
            {field: 'postName', title: '岗位', width: '17%'},
            {field: 'age', title: '年龄', width: '15%'}

        ]],
        toolbar: 'basicLevelToolbar'
    });
}

function initServiceArea() {
    var url='';
    var teamId=$('#teamId').val();
    if(teamId !== undefined){
        url=findTeamRegion+teamId
    }
    $('#serviceArea_table').datagrid({
        url:url,
        fitColumns: true,
        rownumbers: true,
        sortOrder: true,
        striped: true,
        fit: true,
        columns: [[
            {field: 'regionId',  checkbox: true},
            {field: 'regionName', title: '服务区域', width: '25%'},
            {field: 'regionShortName', title: '服务区域简称', width: '24%'},
            {field: 'regionTypeName', title: '服务区域类别', width: '20%'},
            {field: 'regionDeptName', title: '所属单位', width: '20%'}

        ]],
        toolbar: 'serviceAreaToolbar'
    });
}


//服务区域add
function initServiceAreaAddButton() {
    $('#btn_serviceArea_add').on('click',function () {
        WindowManager.openLayer({
            type: 2,
            title: '选择风险区域',
            area: ['1150px', '70%'],
            content: ROOT_PATH + '/risk/region/simpleList.shtml',
            callBack:function(data){//窗口关闭后的回调函数

                var $serviceAreaTable=$('#serviceArea_table');
                var rowsData=$serviceAreaTable.datagrid('getRows');
                var id=data.id;
                for(var i=0; i<rowsData.length;i++){
                    if(id===rowsData[i].serviceAreaId){
                        $serviceAreaTable.datagrid('deleteRow',$serviceAreaTable.datagrid('getRowIndex',rowsData[i]))
                    }
                }
                $serviceAreaTable.datagrid('insertRow',{

                    index: 0,
                    row: {
                        regionId: id,
                        regionName: data.name,
                        regionShortName: data.shortName,
                        regionTypeName: data.typeName,
                        regionDeptName: data.deptName
                    }
                });

            }
        });
    });
}
//领导班子
function initLeaderButton() {
    initUserAddButton('#btn_leader_add','#leader_table',0);
    initUserRemoveButton('#btn_leader_remove','#leader_table');
}
//职能部门
function initFunctionalButton() {
    initUserAddButton('#btn_functional_add','#functional_table',1);
    initUserRemoveButton('#btn_functional_remove','#functional_table');
}
//基层部门
function initBasicLevelButton() {
    initUserAddButton('#btn_basicLevel_add','#basicLevel_table',2);
    initUserRemoveButton('#btn_basicLevel_remove','#basicLevel_table');
}

//删除按钮
function initUserRemoveButton(buttonName,tableName) {
    $(buttonName).on('click', function () {
        var $table = $(tableName);
        var rowData = $table.datagrid('getSelections');
        for (var i = 0; i < rowData.length; i++) {
            var index = $table.datagrid('getRowIndex', rowData[i]);
            $table.datagrid('deleteRow', index);
        }
    });
}
//添加按钮
function initUserAddButton(buttonName,tableName,userType) {
    $(buttonName).on('click',function () {
        WindowManager.openLayer({
            type: 2,
            title: '选择人员信息',
            area: ['1150px', '70%'],
            content: ROOT_PATH + '/permission/user/simpleList.shtml?isMulti=1',
            callBack: function (data) {//窗口关闭后的回调函数


                for (var i = 0; i < data.length; i++) {
                    var userId = data[i].id;
                    var userName = data[i].realName;
                    var userDepartmentList = data[i].userDepartmentList;
                    var postName=data[i].postName;
                    var deptName = [];
                    for (var j = 0; j < userDepartmentList.length; j++) {
                        deptName.push(userDepartmentList[j].deptName);

                    }
                    addUserInfoToUserTable(tableName,userId,userType,userName,postName, deptName.join())
                }



            }
        });
    })
}
//添加数据到表格
function addUserInfoToUserTable(tableName,userId,userType, userName,postName, deptName) {
    var $table = $(tableName);
    var rowData = $table.datagrid('getRows');
    for (var i = 0; i < rowData.length; i++) {
        var index = $table.datagrid('getRowIndex', rowData[i]);
        if (userId === rowData[i].userId) {
            $table.datagrid('deleteRow', index);
        }
    }
    $table.datagrid('insertRow', {
        index: 1,	// 索引从0开始
        row: {
            userId: userId,
            userType: userType,
            userName: userName,
            postName: postName,
            deptName: deptName,
            age: '',
            sex: ''
        }
    });

}
//初始化应急队伍
function initParentTeam() {

    $('#parentId').combogrid({
        editable: false,
        readonly: false,
        panelWidth: 900,
        prompt: '请选择',
        idField: 'id',
        textField: 'name',
        queryParams: {
            sort: 'd.addTime',
            order: 'desc'
        },
        fitColumns: true,
        pagination: true,
        rownumbers: true,
        singleSelect: true,
        sortOrder: true,
        striped: true,
        url: findTeam,
        columns: [[
            {field:'name', title: '队伍名称', width: 10},
            {field:'systemName',title:'建制',width:10},
            {field:'baseName',title:'基地',width:10},
            {field:'typeName',title:'队伍类型',width:10},
            {field:'majorName',title:'专业特色',width:10}
        ]]
    });
}
function hideDiv() {
    $('#leader_div').hide();
    $('#functional_div').hide();
    $('#basicLevel_div').hide();
    $('#serviceArea_div').hide();
}

/**
 * 表单提交
 * @param url
 */
function initSaveButtonClick(url) {

    $('#btn_save').on('click', function () {

        var index = layer.confirm('是否确定保存？', {
            btn: ['确定', '取消'] //按钮
        }, function () {
            $('#submit_form').form('submit', {
                url: url,
                onSubmit: function (param) {
                    var isValid = $(this).form('validate');
                    if (!isValid) {
                        layer.close(index);
                        layer.msg("请正确填写表单")
                    }
                    //领导
                    param["leaderUser"] = JSON.stringify($('#leader_table').datagrid('getRows'));
                    //职能部门
                    param["functionalUser"] = JSON.stringify($('#functional_table').datagrid('getRows'));
                    //基层人员
                    param["basicLevelUser"] = JSON.stringify($('#basicLevel_table').datagrid('getRows'));
                    //危险区域
                    param["teamAndRegion"] = JSON.stringify($('#serviceArea_table').datagrid('getRows'));
                    return $(this).form('validate');
                },
                success: function (result) {
                    var data = $.parseJSON(result);
                    successCallback(data)
                }
            });
        });

    });
}